package binarysearch.test209;

/**
 * 长度最小的子数组
 *
 * @author code_yc
 * @version 1.0
 * @date 2020/7/13 10:23
 */
public class Solution1 {

    // 二分查找
    public int minSubArrayLen(int s, int[] nums) {
        int ans = Integer.MAX_VALUE;
        int sum = 0;
        int l = 0, r = 0;
        while (r < nums.length) {
            if (sum >= s) {
                ans = Math.min(ans, r - l);
                sum -= nums[l++];
            } else {
                sum += nums[r++];
            }
        }
        while (sum >= s) {
            ans = Math.min(ans, r - l);
            sum -= nums[l++];
        }
        return ans == Integer.MAX_VALUE ? 0 : ans;
    }
}
